//
//  SWOrderCell.swift
//  ChildStory
//
//  Created by linhan on 2017/1/20.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWOrderCell: UITableViewCell,ClickActionDelegate
{
    weak var order:SWOrder?
    weak var delegate:ClickActionDelegate?
    
    var progress:CGFloat = 0
    
    private var _change:Bool = true
    private var _cellWidth:CGFloat = 0
    private let ContentInsets:UIEdgeInsets = UIEdgeInsetsMake(0,8,8,8)
    
    private var _contentView:UIView = UIView()
    
    private var _status:SWOrderStatus = .unknow{
        didSet{
            if _status != oldValue
            {
                createBottomView(status: _status)
                _statusView?.status = _status
            }
        }
    }
    
    private var _bottomView:UIView?{
        willSet{
            _bottomView?.removeFromSuperview()
        }
        didSet{
            if let bottomView = _bottomView
            {
                _contentView.addSubview(bottomView)
            }
        }
    }
    
    private var _statusView:SWOrderStatusView?
    
    private var _headerView:UIView = UIView()
    private var _titleLabel:UILabel = UILabel()
    private var _imageView:ImageLoader = ImageLoader()
    private var _orderLabel:UILabel = UILabel()
    private var _dateLabel:UILabel = UILabel()
    private var _priceLabel:UILabel = UILabel()
    
    
    init(style: UITableViewCellStyle, reuseIdentifier: String?, cellWidth:CGFloat)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        _cellWidth = cellWidth
        setup()
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        selectionStyle = .none
        backgroundColor = UIColor.clear
        contentView.backgroundColor = UIColor.clear
        
        let contentWidth:CGFloat = _cellWidth - ContentInsets.left - ContentInsets.right
        let contentHeight:CGFloat = SWThemeStyle.OrderCellHeight - ContentInsets.bottom
        _contentView.frame = CGRectMake(ContentInsets.left, 0, contentWidth, contentHeight)
        _contentView.backgroundColor = UIColor.white
        contentView.addSubview(_contentView)
        
        createHeaderView()
    }
    
    private func createHeaderView()
    {
        _headerView.frame = CGRectMake(0, 0, _cellWidth, 280)
        _contentView.addSubview(_headerView)
        
        _imageView.frame = CGRectMake(0, 0, 40, 40)
        _headerView.addSubview(_imageView)
        
        let titleLabelX:CGFloat = _imageView.right + 10
        let titleLabelWidth:CGFloat = _contentView.width * 0.5
        _titleLabel.frame = CGRectMake(titleLabelX, 0, titleLabelWidth, 18)
        _titleLabel.font = UIFont.systemFont(ofSize: 14)
        _headerView.addSubview(_titleLabel)
        
        _orderLabel.frame = CGRectMake(_contentView.width * 0.5, 0, _contentView.width * 0.5, 16)
        _orderLabel.font = UIFont.systemFont(ofSize: 12)
        _orderLabel.textColor = UIColor.darkGray
        _headerView.addSubview(_orderLabel)
        
        _dateLabel.frame = CGRectMake(_orderLabel.x, _orderLabel.bottom + 10, _orderLabel.width, 16)
        _dateLabel.font = UIFont.systemFont(ofSize: 12)
        _dateLabel.textColor = UIColor.darkGray
        _headerView.addSubview(_dateLabel)
        
        _priceLabel.frame = CGRectMake(_orderLabel.x, _dateLabel.bottom + 10, _orderLabel.width, 16)
        _priceLabel.font = UIFont.systemFont(ofSize: 12)
        _priceLabel.textColor = UIColor.darkGray
        _headerView.addSubview(_priceLabel)
        
        let statusViewHeight:CGFloat = 50
        let statusView:SWOrderStatusView = SWOrderStatusView(frame: CGRectMake(0,_dateLabel.bottom + 10,_contentView.width, statusViewHeight))
        _headerView.addSubview(statusView)
        _statusView = statusView
        
        _headerView.height = statusView.bottom
    }
    
    //根据不同状态创建不同的底部功能区
    private func createBottomView(status:SWOrderStatus)
    {
        let bottomViewY:CGFloat = _headerView.bottom
        let bottomViewHeight:CGFloat = 40
        let bottomViewFrame = CGRectMake(0, bottomViewY, _contentView.width, bottomViewHeight)
        if status == .unpaid
        {
            let payView:SWOrderCellPayView = SWOrderCellPayView(frame: bottomViewFrame)
            payView.delegate = self
            
            _bottomView = payView
        }
        else if status == .purchased
        {
            let uploadingView = SWOrderCellUploadingView(frame: bottomViewFrame)
            _bottomView = uploadingView
        }
        else if status == .making
        {
            let makingView:SWOrderCellMakingView = SWOrderCellMakingView(frame: bottomViewFrame)
            _bottomView = makingView
        }
    }
    
    private func updateView(order:SWOrder)
    {
        _imageView.load("http://mmbiz.qpic.cn/mmbiz_jpg/yhLXShsZlamwfumuM5V5YCMvJcOq9L6UYQjBF5vM5BOX4tmtjnNQ7NyJIC6GBuuLo7SItibetMK9JmsERZmKTuQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1")
        
        if let product = order.products.flatMap({$0 as? SWProduct}).first
        {
            _titleLabel.text = product.title
        }
        
        let orderID:String = order.orderID ?? ""
        _orderLabel.text = "订单:\(orderID)"
        
        let date:String = (order.creationDate as NSDate).formattedDate(withFormat: "YYYY-MM-dd")
        _dateLabel.text = "下单时间：\(date)"
        
        _priceLabel.text = "订单金额：\(order.price)"
        
        if let uploadingView = _bottomView as? SWOrderCellUploadingView
        {
            uploadingView.progress = progress
        }
    }
    
    func view(_ view:UIView, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        delegate?.view(self, click: action, argument: aArgument)
    }
    
    override func prepareForReuse()
    {
        super.prepareForReuse()
        _change = true
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        
        if let order = order , _change
        {
            _change = false
            
            _status = order.status
            updateView(order: order)
        }
    }
    
    
    
    
}


fileprivate class SWOrderCellPayView:UIView
{
    weak var delegate:ClickActionDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        let payBtn:UIButton = UIButton(type: .system)
        payBtn.setTitle("去支付", for: .normal)
        payBtn.sizeToFit()
        payBtn.center = bounds.center
        payBtn.addTarget(self, action: #selector(payBtnTapped), for: .touchUpInside)
        addSubview(payBtn)
    }
    
    @objc private func payBtnTapped()
    {
        delegate?.view(self, click: CallbackAction.Pay, argument: nil)
    }
    
}


fileprivate class SWOrderCellUploadingView:UIView
{
    weak var delegate:ClickActionDelegate?
    
    var progress:CGFloat = 0{
        didSet{
            let p:Int = Int(progress * 100)
            _progressLabel.text = "上传进度\(p)%"
        }
    }
    
    private var _progressLabel:UILabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        _progressLabel.textColor = UIColor.darkGray
        _progressLabel.font = UIFont.systemFont(ofSize: 14)
        _progressLabel.frame = CGRectMake(0, 0, width, 18)
        addSubview(_progressLabel)
        
        progress = 0
    }
    
}


fileprivate class SWOrderCellMakingView:UIView
{
    private var _progressLabel:UILabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        _progressLabel.textColor = UIColor.darkGray
        _progressLabel.font = UIFont.systemFont(ofSize: 14)
        _progressLabel.text = "咿呀正在拼命赶工"
        _progressLabel.sizeToFit()
        _progressLabel.center = bounds.center
        addSubview(_progressLabel)
    }
    
}
